package com.sr.examination.user.base;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.sr.examination.MyApplication;
import com.sr.examination.R;
import com.sr.examination.common.event.UserHeadEvent;
import com.sr.examination.net.Net;
import com.sr.examination.user.Account;
import com.sr.examination.user.UpImageModel;
import com.sr.examination.user.widget.GenderPop;
import com.tl.commonlibrary.event.EventUtil;
import com.tl.commonlibrary.network.ErrorResponse;
import com.tl.commonlibrary.network.RequestListener;
import com.tl.commonlibrary.network.bean.base.BaseBean;
import com.tl.commonlibrary.tool.ImageTools;
import com.tl.commonlibrary.tool.UIUtils;
import com.tl.commonlibrary.ui.beans.User;
import com.tl.commonlibrary.ui.permission.PermissionActivity;
import com.tl.commonlibrary.ui.widget.CustomAlertDialog;
import com.tl.commonlibrary.ui.widget.DialogInput;
import com.tl.commonlibrary.ui.widget.GlideRoundTransform;
import com.tl.commonlibrary.ui.widget.PhotoSelectPopupWindow;
import com.tl.commonlibrary.ui.widget.TitleBar;
import com.yancy.imageselector.ImageSelector;
import com.yancy.imageselector.ImageSelectorActivity;

import java.util.HashMap;
import java.util.List;

import retrofit2.Call;

/**
 * Created by JongSung on 18/3/3.
 */

public class UserInfoActivity extends PermissionActivity {
    public static void start(Context context) {
        if (Account.isLogged(context)) {
            Intent starter = new Intent(context, UserInfoActivity.class);
            context.startActivity(starter);
        }
    }

    private HashMap<String, Object> postParam = new HashMap<>();
    private TextView genderTView, nickNameTView, phoneTView, mailTView;
    private DialogInput nameDialog, mailDialog;
    private CustomAlertDialog exitDialog;
    private PhotoSelectPopupWindow mComXingzhiPopupWindow;
    private ImageView userHeadIView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_user_info);
        setTitle(getString(R.string.user_info));
        genderTView = findViewById(R.id.genderTView);
        nickNameTView = findViewById(R.id.nickNameTView);
        phoneTView = findViewById(R.id.phoneTView);
        mailTView = findViewById(R.id.mailTView);
        userHeadIView = findViewById(R.id.userHeadIView);
        userHeadIView.setOnClickListener(this);
        getTitleBar().addAction(new TitleBar.TextAction(getString(R.string.save)) {
            @Override
            public void performAction(View view) {
                postUserInfo();
            }
        });
        setUserInfo();
        MyApplication.get().updateUserInfo(new MyApplication.OnUpdateUserInfoListener() {
            @Override
            public void onUpdateUserInfo(User user) {
                setUserInfo();
            }
        });
    }

    private void setUserInfo() {
        User user = Account.getUser();
        if (user == null) {
            return;
        }
        genderTView.setText(user.getGender() == User.GENDER_MAN ? R.string.gender_man : (user.getGender() == User.GENDER_WOMAN ? R.string.gender_woman : R.string.gender_unknown));
        nickNameTView.setText(user.getNickname());
        phoneTView.setText(user.getMobile());
        mailTView.setText(user.getEmail());
        Glide.with(this).load(user.getProfilePhoto()).error(R.mipmap.ic_head_default).placeholder(R.mipmap.ic_head_default)
                .transform(new GlideRoundTransform(this, 70))
                .into(userHeadIView);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.userHeadIView:
                showHeadPop();
                break;
        }
    }

    @Override
    public void onFragmentTrigger(int tag, Bundle bundle) {

    }

    public void onGenderClick(View view) {
        GenderPop genderPop = new GenderPop(this);
        genderPop.setOnGenderListener(new GenderPop.OnGenderListener() {
            @Override
            public void onGender(int gender, String genderName) {
                ((TextView) findViewById(R.id.genderTView)).setText(genderName);
                if (gender == Account.getUser().getGender()) {
                    postParam.remove("gender");
                } else {
                    postParam.put("gender", gender);
                }
            }
        });
        genderPop.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
    }

    public void onNickNameClick(View view) {
        if (nameDialog == null) {
            nameDialog = new DialogInput(context);
            nameDialog.setListener(new DialogInput.OnInputDialogClickListener() {
                @Override
                public void onLeftBtnClicked(View view, String content) {

                }

                @Override
                public void onRightBtnClicked(View view, String content) {
                    if (!TextUtils.isEmpty(content)) {
                        if (content.equals(Account.getUser().getNickname())) {
                            postParam.remove("nickname");
                        } else {
                            postParam.put("nickname", content);
                            nickNameTView.setText(content);
                        }
                    }
                }
            });
        }
        nameDialog.show();
        nameDialog.getContentView().setSingleLine(true);
        nameDialog.getContentView().setMaxLines(1);
    }


    public void onMailClick(View view) {
        if (mailDialog == null) {
            mailDialog = new DialogInput(context);
            mailDialog.setListener(new DialogInput.OnInputDialogClickListener() {
                @Override
                public void onLeftBtnClicked(View view, String content) {

                }

                @Override
                public void onRightBtnClicked(View view, String content) {
                    if (!TextUtils.isEmpty(content)) {
                        if (content.equals(Account.getUser().getEmail())) {
                            postParam.remove("email");
                        } else {
                            postParam.put("email", content);
                            User user = Account.getUser();
                            user.setEmail(content);
                            mailTView.setText(content);
                        }
                    }
                }
            });
        }
        mailDialog.show();
        mailDialog.getContentView().setSingleLine(true);
        mailDialog.getContentView().setMaxLines(1);
    }

    private void postUserInfo() {
        if (postParam == null || postParam.size() <= 0) {
            finish();
            return;
        }
        if (userHeadNativeUrl != null && !postParam.containsKey("profilePhoto")) {
            UIUtils.showToast("头像还没上传成功,已忽略头像更改", Toast.LENGTH_LONG);
        }
        showProgressDialog(getString(R.string.progress_post_user_info));
        Net.postUserInfo(postParam, new RequestListener<BaseBean>() {
            @Override
            public void onSuccess(Call<BaseBean> call, BaseBean response) {
                if (response.isSuccessful()) {
                    if (MyApplication.get() != null) {
                        MyApplication.get().updateUserInfo(new MyApplication.OnUpdateUserInfoListener() {
                            @Override
                            public void onUpdateUserInfo(User user) {
                                UIUtils.showToast(getString(R.string.post_user_info_success));
                                dismissAll();
                                finish();
                            }
                        });
                    } else {
                        dismissAll();
                        finish();
                    }
                } else {
                    dismissAll();
                }
            }

            @Override
            public void onFailed(Call<BaseBean> call, ErrorResponse errorResponse) {
                dismissAll();
            }
        });
    }

    @Override
    public void back() {
        if (!userInfoChanged()) {
            super.back();
        }
    }

    private boolean userInfoChanged() {
        if (postParam != null && postParam.size() > 0) {
            if (exitDialog == null) {
                exitDialog = new CustomAlertDialog(context);
                exitDialog.setContent(getString(R.string.hint_post_user_info));
                exitDialog.setListener(new CustomAlertDialog.OnAlertClickListener() {
                    @Override
                    public void onRightClicked(View view) {
                        finish();
                    }

                    @Override
                    public void onLeftClicked(View view) {

                    }
                });
            }
            exitDialog.show();
            return true;
        }
        return false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (userInfoChanged()) {
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showHeadPop() {
        if (mComXingzhiPopupWindow == null) {
            mComXingzhiPopupWindow = new PhotoSelectPopupWindow(this);
            mComXingzhiPopupWindow.setOnPhotoSelectListener(new PhotoSelectPopupWindow.OnPhotoSelectListener() {
                @Override
                public void takePhoto() {
                    onTakePhoto();
                }

                @Override
                public void selectPhoto() {
                    selectPhotoNow();
                }
            });
        }
        mComXingzhiPopupWindow.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);

    }

    final int TAKE_PICTURE = 1;

    private void onTakePhoto() {
        requestPermission(Manifest.permission.CAMERA, PermissionActivity.PERMISSION_REQUEST_CODE_CAMERA);
//        startActivityForResult(new Intent("android.media.action.IMAGE_CAPTURE"), TAKE_PICTURE);
    }

    String userHeadNativeUrl;

    private void selectPhotoNow() {
        getUpImagePresent();
        mUpImagePresenter.changePortrait(null);
    }

    private UpImageModel mUpImagePresenter;

    private UpImageModel getUpImagePresent() {
        if (mUpImagePresenter == null) {
            mUpImagePresenter = new UpImageModel(this, false);
            mUpImagePresenter.setAvatarUploadedListener(new UpImageModel.IAvatarUploadedListener() {
                @Override
                public void onAvatarUploadedSucceed(String url) {
                    postParam.put("profilePhoto", url);
                    userHeadIView.setAlpha(1.0f);
                }
            });
        }
        return mUpImagePresenter;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            if (requestCode == ImageSelector.IMAGE_REQUEST_CODE) {
                // Get Image Path List
                List<String> pathList = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);
                String path = pathList.get(pathList.size() - 1);
                userHeadNativeUrl = path;
                getUpImagePresent().startUpload(path);
                Glide.with(this).load(path).error(R.mipmap.ic_head_default).placeholder(R.mipmap.ic_head_default)
                        .transform(new GlideRoundTransform(this, 70))
                        .into(userHeadIView);
                userHeadIView.setAlpha(0.4f);
            } else if (requestCode == TAKE_PICTURE) {

                if (data.getData() != null || data.getExtras() != null) { //防止没有返回结果
                    String photo = null;
                    Uri uri = data.getData();
                    if (uri != null) {
                        photo = uri.getPath(); //拿到图片
                    }
                    if (photo == null) {
                        Bundle bundle = data.getExtras();
                        if (bundle != null) {
                            Bitmap photoBit = (Bitmap) bundle.get("data");
                            if (photoBit != null && Environment.isExternalStorageEmulated()) {
                                String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/carUp";
                                String name = System.currentTimeMillis() + ".jpg";
                                photo = path + "/" + name;
                                ImageTools.savePhotoToSDCard(photoBit, path, name);
                            }
                        } else {
                            Toast.makeText(getApplicationContext(), "找不到图片", Toast.LENGTH_SHORT).show();
                        }
                    }

                    if (photo != null) {
                        //上传图片
                        userHeadNativeUrl = photo;
                        getUpImagePresent().startUpload(photo);
//                        Picasso.with(this).load(photo).error(R.mipmap.ic_head_default).placeholder(R.mipmap.ic_head_default)
////                        .transform(new GlideRoundTransform(this, 70))
//                                .into(userHeadIView);
                        Glide.with(this).load(photo).diskCacheStrategy(DiskCacheStrategy.ALL)
                                .transform(new GlideRoundTransform(this, 70))
                                .into(userHeadIView);
                        userHeadIView.setAlpha(0.4f);
                    }
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (nameDialog != null) {
            nameDialog.dismiss();
            nameDialog = null;
        }
        if (mailDialog != null) {
            mailDialog.dismiss();
            mailDialog = null;
        }
        if (exitDialog != null) {
            exitDialog.dismiss();
            exitDialog = null;
        }
    }

    @Override
    public void permissionSuccess(int requestCode) {
        switch (requestCode) {
            case PermissionActivity.PERMISSION_REQUEST_CODE_CAMERA:
                //请求相机权限后开始调用相机拍照
                startActivityForResult(new Intent("android.media.action.IMAGE_CAPTURE"), TAKE_PICTURE);
                break;
        }
    }

    @Override
    public void permissionFailed(int requestCode) {

    }
}
